package com.mperon.bean.hb;

import com.mperon.bean.Bean;
import com.mperon.bean.Car;
import com.mperon.bean.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

/**
 *
 * @author Marcos Peron
 */
public class HibernateUtil {

    private static final SessionFactory factory;
    private static final ServiceRegistry serviceRegistry;

    static {
        Configuration config = getConfiguration();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(
                config.getProperties()).buildServiceRegistry();

        config.setSessionFactoryObserver(new SessionFactoryObserver() {

            @Override
            public void sessionFactoryCreated(SessionFactory factory) {
            }

            @Override
            public void sessionFactoryClosed(SessionFactory factory) {
                ServiceRegistryBuilder.destroy(serviceRegistry);
            }
        });

        factory = config.buildSessionFactory(serviceRegistry);
    }

    /**
     *
     * @return hibernate configuration
     */
    private static Configuration getConfiguration() {

        Configuration cfg = new Configuration();
        cfg.setNamingStrategy(new ImprovedNamingStrategy());
        cfg.configure();
        cfg.addAnnotatedClass(Bean.class);
        cfg.addAnnotatedClass(Person.class);
        cfg.addAnnotatedClass(Car.class);
        return cfg;
    }

    /**
     *
     * @return
     */
    public static Session openSession() {
        return factory.openSession();
    }

    /**
     *
     * @param script
     * @param doUpdate
     */
    public static void createOrUpdateSchema(boolean script, boolean doUpdate) {
        SchemaUpdate schema = new SchemaUpdate(getConfiguration());
        schema.execute(script, doUpdate);
    }
}